import { useCallback } from 'react';
import { useModel } from 'umi';
import { loginApi, getAuthUserApi, logoutApi } from '@/services/auth/auth';
import { NORMAL_CODE } from '@/constants';

export default () => {
  const { initialState, setInitialState } = useModel('@@initialState');

  // 登录
  const login = useCallback(async (param,attach={}) => {
    const res = await loginApi(param,attach.options??{});
    if (res.code === NORMAL_CODE) {
      //设置token
      localStorage.setItem('token', res.data.access_token);
    }
    return res;
  }, []);

  // 获取当前用户信息
  const getAuthInfo = useCallback(async (param,attach={}) => {
    const res = await getAuthUserApi(param,attach.options??{});
    if (res.code !== NORMAL_CODE) {
      await setInitialState((s) => ({
        ...s,
        authData: {},
      }));
    } else {
      await setInitialState((s) => ({
        ...s,
        authData: res.data,
      }));
    }
    return res;
  }, []);

  // 退出
  const logout = useCallback(async (param,attach={}) => {
    const res = await logoutApi(param,attach.options??{});
    if (res.code == NORMAL_CODE) {
      //设置token
      localStorage.setItem('token', '');
      await setInitialState((s) => ({
        ...s,
        authData: {},
      }));
    }
    return res;
  }, []);

  return {
    login,
    getAuthInfo,
    logout,
  };
};
